
import { GetTokenFn,GetNewInfo } from '../api/sys/userCode';
import { GetPermCode } from '../api/sys/user';
import { defineStore } from 'pinia';
import { store } from '../store';
import { setToken_Code, setToken_AccToken, setToken_Name,setToken_Uid } from '../utils/cookies'
import Cookies from 'js-cookie';

interface LoginState {
  login_Code: ''
  login_AccToken: ''
  login_Uid: ''
  login_name: ''

}

export const useLoginStore = defineStore({
  id: 'app-login',
  state: (): LoginState => ({
    // user info
    login_Code: '',
    login_Uid:'',
    // token
    login_AccToken: '',
    // Whether the login expired
    login_name: '',
  }),
  getters: {
    getLoginCode(): string {
      return this.login_Code  
    },
    getLoginAccToken(): string {
      return this.login_AccToken 
    },
    getLoginUid(): string {
      return this.login_AccToken 
    },
    getLoginName(): string {
      return this.login_name;
    }
  },
  actions: {
    setLoginCode(info: string ) {
      this.login_Code = info;
      setToken_Code(info);
    },
    setLoginAccToken(info) {
      this.login_AccToken = info;
      setToken_AccToken(info);
    },
    setLoginUid(info) {
      this.login_Uid = info;
      setToken_Uid(info);
    },
    setLoginName(info) {
      this.login_name = info;
      setToken_Name(info);
    },
    /**
     * @description: login
     */
      async login_Acctoken_fn(code) {
      try {
        
        this.setLoginCode(code)
        
        const accToken_Data = await GetTokenFn(code);
        //console.log("获取的token"+accToken_Data);
        
        // save token 
        this.setLoginAccToken(accToken_Data.access_token);
        this.setLoginUid(accToken_Data.uid);
        // get user info
        
        const userInfo =await this.login_name_fn(accToken_Data);
        return accToken_Data;
      } catch (error) {
        return Promise.reject(error);
      }
    },

    async login_name_fn(data) {
      try {
        const name_Data =await GetNewInfo(data);

        // save token
        this.setLoginName(name_Data.loginName);
        // this.setLoginName('glodon5');
        // get user info
        
        // const userInfo = await this.getUserInfoAction(data);


        return name_Data;
      } catch (error) {
        return Promise.reject(error);
      }
    },

  },
});

// Need to be used outside the setup
export function useLoginStoreWithOut() {
  return useLoginStore(store);
}
